import { configureStore } from '@reduxjs/toolkit';
import { testReducer } from './test';
import { userReducer } from './user';
import { chatReducer } from './chat';
import { useSelector } from 'react-redux';

// 根store
export const store = configureStore({
  reducer: {
    test: testReducer,
    user: userReducer,
    chat: chatReducer,
  },
});

export type IRootState = ReturnType<typeof store.getState>;

// 导出类型
export type ITestState = IRootState['test'];
export type IUserState = IRootState['user'];
export type IChatState = IRootState['chat'];

export type IAppDispatch = typeof store.dispatch;

// 获取某个state的rootState值
export function useRootState<T extends keyof IRootState>(key?: T) {
  const value = useSelector<IRootState, IRootState[T] | IRootState>((state) => {
    return key ? state[key] : state;
  });

  return value as unknown as typeof key extends undefined
    ? IRootState
    : IRootState[T];
}
